import * as r from '../base_rule';
import { readFileSync, existsSync } from 'fs';
const meta = new r.QueryMeta({
  priority: 99,
  region: 'global',
  name: "unsafe ref in packages",
  description: "unsafe_ref_in_packages detects unsafe references in `oh-package.json5` files.",
  severity: 'medium',
  tags: ['reference', 'security', 'package'],
})
const dep_checks = (name: string, desc: string, version: number): string | undefined => {
  if (!name) return
  if (name.indexOf('evil') !== -1) {
    return `Unsafe package detected: ${name} with version ${version}`;
  }
  if (name === '@ohos/axios') {
    if (version < 2.4) return `@ohos/axios version ${version} is too low, please upgrade to 2.4 or higher`
  }
}
export const unsafe_ref_in_packages = r.dsl.create(meta, async function (q) {
  const project_folder = r.state.tsConfig.options.project_folder || process.cwd();
  const ohPackagePath = `${project_folder}/oh-package.json5`;
  if (!existsSync(ohPackagePath)) return q;
  const ohPackageContent = readFileSync(ohPackagePath).toString();
  if (!ohPackageContent) return q;
  const json5 = require('json5');
  const ohPackage = json5.parse(ohPackageContent);
  const allDeps = { ...ohPackage.dependencies, ...ohPackage.devDependencies };
  const unsafeRefs = Object.entries(allDeps).map(([name, version]) => {
    const ver: string = version as string
    const result = { ver, name, desc: version, result: null, }
    const val_version = ver && ver.match(/^\d+(\.\d+)?$/) ? parseFloat(ver) : 0
    result.result = dep_checks(name, ver, val_version)
    return result
  }).filter(x => x.result);
  if (unsafeRefs.length === 0) return q;
  this.report({
    name: meta.name,
    result: `Unsafe references found in oh-package.json5: ${unsafeRefs.map(x => `[${x.name}(${x.desc}):${x.result}]`).join(', ')}`,
    milliseconds: 0, // Execution time is not measured here
  })
  return q
})
